﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;

namespace SharePointAccelerators.EventReceiversHelper.ListEventReceivers
{
    [ToolboxItemAttribute(false)]
    public class ListEventReceivers : WebPart
    {
        protected DropDownList _dropDownList = new DropDownList();
        protected Label _eventReceveiversLabel = new Label();

        protected override void CreateChildControls()
        {
            if (!Page.IsPostBack)
            {
                
                foreach (SPList list in SPContext.Current.Web.Lists)
                {
                    _dropDownList.Items.Add(new ListItem(list.Title, list.ID.ToString()));
                }

                //_dropDownList.EnableViewState = true;

                //_eventReceveiversLabel.EnableViewState = true;

               
            }
        }

        protected override void OnInit(EventArgs e)
        {
            _dropDownList = new DropDownList();
            _dropDownList.ID = "_dropDownList";
            _eventReceveiversLabel = new Label();
            _eventReceveiversLabel.ID = "_eventReceveiversLabel";

            _dropDownList.SelectedIndexChanged += new EventHandler(dropDownList_SelectedIndexChanged);
            _dropDownList.AutoPostBack = true;
            _dropDownList.EnableViewState = true;

            this.Controls.Add(_eventReceveiversLabel);
            this.Controls.Add(_dropDownList);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.EnsureChildControls();
        }

        protected void dropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label eventReceiversLabel = (Label)this.FindControl("_eventReceveiversLabel");
            DropDownList dropDownList= (DropDownList)this.FindControl("_dropDownList");

            StringBuilder eventReceivers = new StringBuilder();
            if (SPContext.Current.Web.Lists[new Guid(dropDownList.SelectedValue.ToString())]!=null)
            {
                SPList list = SPContext.Current.Web.Lists[new Guid(dropDownList.SelectedValue.ToString())];

                foreach (SPEventReceiverDefinition eventReceiver in list.EventReceivers)
                {
                    eventReceivers.Append(string.Format("{0}:{1},{2}<br/>", eventReceiver.SequenceNumber, eventReceiver.Assembly, eventReceiver.Class));
                }
            }

            eventReceiversLabel.Text = eventReceivers.ToString();
        }
    }
}
